package com.qkl.xiatang.app.service.impl;

import com.qkl.xiatang.app.config.AppConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Service
@EnableScheduling
@Slf4j
public class MqttClientService {

    private MqttClient mqttClient;

    @Autowired
    private MqttCallback mqttCallback;

    @Autowired
    private AppConfig appConfig;

    @PostConstruct
    public void initMqttClient(){
        if(!appConfig.isMqttEnable()){
            log.info("================MqttClient未开启");
            return;
        }
        String subTopic = this.trimToEmpty(appConfig.getMqttSubTopic());
        String broker = this.trimToEmpty(appConfig.getMqttBroker());
        String clientId = this.trimToEmpty(appConfig.getMqttClientId());
        String userName = this.trimToEmpty(appConfig.getMqttUserName());
        String pwd = this.trimToEmpty(appConfig.getMqttPwd());
        MemoryPersistence persistence = new MemoryPersistence();
        try{

            mqttClient = new MqttClient(broker, clientId, persistence);

            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName(userName);
            if(StringUtils.isNotEmpty(pwd)){
                connOpts.setPassword(pwd.toCharArray());
            }
            // 保留会话
            connOpts.setCleanSession(false);
            connOpts.setAutomaticReconnect(true);

            // 设置回调
            mqttClient.setCallback(mqttCallback);

            // 建立连接
            mqttClient.connect(connOpts);
            // 订阅
            mqttClient.subscribe(subTopic);
            log.info("================MqttClient连接成功");

        }catch (Exception e){
            log.error("================MqttClient连接失败.initMqttCall exception.");
            e.printStackTrace();
        }
    }

    //第一次任务延迟10分钟启动，之后每隔10分钟执行
    @Scheduled(fixedDelay=10*60*1000,initialDelay=10*60*1000)
    public void reconnectMqttCall(){
        if(null == mqttClient || !mqttClient.isConnected() ){
            log.info("================MqttClient重连");
            this.initMqttClient();
        }
    }

    @PreDestroy
    public void closeMqttCall(){
        if(null != mqttClient){
            try {
                mqttClient.disconnect();
                log.info("================MqttClient关闭连接");
            }catch (Exception e){
                log.error("closeMqttCall exception.");
                e.printStackTrace();
            }
        }
    }

    private String trimToEmpty(String s){
        return StringUtils.trimToEmpty(s);
    }


}
